package org.backend.canteenbackend.controller;

import lombok.Data;
import org.backend.canteenbackend.common.CommonResponse;
import org.backend.canteenbackend.service.OrderService;
import org.backend.canteenbackend.vo.LineItemVO;
import org.backend.canteenbackend.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderManageController {

    @Autowired
    private OrderService orderService;

    // 订单详情响应DTO
    @Data
    public class OrderDetailResponse {
        private OrderVO order;
        private List<LineItemVO> lineItems;
    }

    // 获取所有订单列表
    @GetMapping
    @ResponseBody
    public CommonResponse<List<OrderVO>> getAllOrders() {
        List<OrderVO> orders = orderService.findOrderVOs();
        return CommonResponse.createForSuccess(orders);
    }

    // 订单详情接口
    @GetMapping("/{orderId}/detail")
    @ResponseBody
    public CommonResponse<OrderDetailResponse> getOrderDetail(@PathVariable("orderId") Integer orderId) {
        try {
            // 获取订单基本信息
            OrderVO order = orderService.findOrderVOByOrderId(orderId);
            if (order == null) {
                return CommonResponse.createForError("订单不存在");
            }

            // 丰富订单价格信息
            order = orderService.enrichOrderWithListPrice(order);

            // 获取订单商品项列表
            List<LineItemVO> lineItems = orderService.findLineItemVOsByOrderId(orderId);

            // 构建响应对象
            OrderDetailResponse response = new OrderDetailResponse();
            response.setOrder(order);
            response.setLineItems(lineItems);

            return CommonResponse.createForSuccess(response);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    // 更新订单状态
    @PostMapping("/{orderId}/status")
    @ResponseBody
    public CommonResponse<Map<String, Object>> updateOrderStatus(@PathVariable("orderId") Integer orderId) {
        Map<String, Object> response = new HashMap<>();
        try {
            OrderVO order = orderService.findOrderVOByOrderId(orderId);
            String currentStatus = order.getOrderStatus().getStatus();
            String newStatus = "P".equals(currentStatus) ? "S" : "P";
            orderService.updateStatusByOrderid(orderId, newStatus);

            response.put("newStatus", newStatus);
            return CommonResponse.createForSuccess(response);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    // 删除订单
    @DeleteMapping("/{orderId}")
    @ResponseBody
    public CommonResponse<Void> deleteOrder(@PathVariable("orderId") Integer orderId) {
        try {
            boolean success = orderService.deleteOrderByOrderid(orderId);
            if (!success) {
                return CommonResponse.createForError("订单删除失败");
            }
            return CommonResponse.createForSuccess(null);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    // 通过订单ID查询订单详情
    @GetMapping("/{orderId}")
    @ResponseBody
    public CommonResponse<OrderVO> getOrderById(@PathVariable("orderId") Integer orderId) {
        try {
            OrderVO orderVO = orderService.findOrderVOByOrderId(orderId);
            if (orderVO == null) {
                return CommonResponse.createForError("订单不存在");
            }
            return CommonResponse.createForSuccess(orderVO);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    // 根据用户ID查询订单
    @GetMapping("/user/{userId}")
    @ResponseBody
    public CommonResponse<List<OrderVO>> getOrdersByUser(@PathVariable("userId") String userId) {
        try {
            List<OrderVO> orders = orderService.findOrderVOsByUserId(userId);
            return CommonResponse.createForSuccess(orders);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

    // 更新订单地址
    @PostMapping("/{orderId}/address")
    @ResponseBody
    public CommonResponse<Void> updateOrderAddress(
            @PathVariable("orderId") Integer orderId,
            @RequestBody Map<String, String> addressData) {

        try {
            orderService.updateAddressByOrderid(
                    orderId,
                    addressData.get("shipAddress1"),
                    addressData.get("shipAddress2"),
                    addressData.get("shipCity"),
                    addressData.get("shipState"),
                    addressData.get("shipZip")
            );
            return CommonResponse.createForSuccess(null);
        } catch (Exception e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }

}
